package htmltags;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTag;
import javax.servlet.jsp.tagext.TagSupport;

public class SelectTag extends TagSupport implements BodyTag {
	private List<String> items;
	private String contenido;
	int contador = 0;
	
	public SelectTag() {
		items = new ArrayList<String>();
		items.add("1");
		items.add("2");
		items.add("3");
	}
	
	@Override
	public int doStartTag() throws JspException {
		contador = 0;
		JspWriter out = pageContext.getOut();
		try {
			out.print("<select name='elemento'>");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return EVAL_BODY_INCLUDE;
	}
	@Override
	public int doEndTag() throws JspException {
		JspWriter out = pageContext.getOut();
		try {
			out.print("</select>");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return EVAL_PAGE;
	}
	
	@Override
	public int doAfterBody() throws JspException {
		contador++;
		if (items !=null && contador <= items.size()){
			JspWriter out = pageContext.getOut();
			try {
				out.print("<option>" + items.get(contador-1) + "</option>");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return EVAL_BODY_AGAIN;
		}
		return SKIP_BODY;
	}
	
	@Override
	public void doInitBody() throws JspException {
		// TODO Auto-generated method stub
	}
	@Override
	public void setBodyContent(BodyContent arg0) {
		contenido = arg0.getString();
	}
	public List<String> getItems() {
		return items;
	}
	public void setItems(List<String> items) {
		this.items = items;
	}	
}
